package com.atguigu.study.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.entities.School;
import com.atguigu.study.service.SchoolService;
import com.atguigu.study.mapper.SchoolMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author wangs
* @description 针对表【tb_school】的数据库操作Service实现
* @createDate 2024-09-03 22:59:40
*/
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School>
    implements SchoolService{

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String SCHOOL_LIST_KEY = "schoolList";

    @Override
    public List<School> listByRedis() {
        // 先从 Redis 中获取
        List<School> schoolList = (List<School>) redisTemplate.opsForValue().get(SCHOOL_LIST_KEY);

        // 如果 Redis 中没有数据，则从 MySQL 中查询并存入 Redis
        if (schoolList == null) {
            schoolList = schoolMapper.findAllTbSchool();
            redisTemplate.opsForValue().set(SCHOOL_LIST_KEY, schoolList, 30, TimeUnit.MINUTES); // 设置缓存时间为 30 分钟
        }
        return schoolList;
    }
}
